var isDefaultAddress = false,
	province = getProvince(),
	city = getCity(),
	district = getDistrict(),
	pickProvinceIndex = -1,
	pickCityIndex = -1,
	pickDistrictIndex = -1;
var expressArea, areaCont, areaList = $("#areaList");
//areaTop = areaList.offset().top;

$(() => {
	initProvince(1);
	initListener();
})

initListener = () => {
	$("#save_address").on('click', () => {
		saveAddress();
	});
	$("#pick_area").on('click', () => {
		onPickArea();
	});
	$("#location").on('click', () => {
		onLocation();
	});
	$("#name").bind('input propertychange', (event) => {
		let value = event.target.value;
		if (value && value.length > 0) {
			$("#clear_name").show()
		} else{
			$("#clear_name").hide()
		}
	});
	$("#clear_name").on('click', () => {
		$("#name").val('');
		$("#clear_name").hide()
	});
	$("#phone").bind('input propertychange', (event) => {
		let value = event.target.value;
		if (value && value.length > 0) {
			$("#clear_phone").show()
		} else{
			$("#clear_phone").hide()
		}
	});
	$("#clear_phone").on('click', () => {
		$("#phone").val('');
		$("#clear_phone").hide()
	});
	$("#address").bind('input propertychange', (event) => {
		let value = event.target.value;
		let max = event.target.maxLength;
		$("#address_len").html(value.length + '/' + max);
		
		if (value && value.length > 0) {
			$("#clear_address").show()
		} else{
			$("#clear_address").hide()
		}
	});
	$("#clear_address").on('click', () => {
		$("#address").val('');
		$("#clear_address").hide();
		$("#address_len").html('');
	});
	$("#def_address").bind('input propertychange', (event) => {
		isDefaultAddress = event.target.checked;
	});

	$.fn.extend({
		/* 单选框 */
		tagRadio: function() {
			let tagLabel = $(this);

			tagLabel.click(function() {
				tagLabel.siblings("div").removeClass("radio_actived");
				$(this).siblings("div").addClass("radio_actived");
			});
		}

	});
	$("input[name='tag']").tagRadio();
}

/*初始化省份*/
initProvince = (flag) => {
	$("#areaList").html('');
	let itemHtml = ``;
	for (var i = 0; i < province.length; i++) {
		itemHtml += `<div class="xpopup_list_item" onclick="selectProvince('${i}','1')">${province[i]}</div>`;
	}
	$("#areaList").html(itemHtml);
	$("#areaBox").scrollTop(0);
	if (flag) {
		$('.xpopup_result .province').html(" ").removeClass("current");
	} else {
		if ($('.xpopup_result .province').html() != '')
			$('.xpopup_result .province').addClass("current");
	}
	$('.xpopup_result .city').html("").removeClass("current").attr("onClick", ";");
	$('.xpopup_result .district').html("").removeClass("current").attr("onClick", ";");
}

selectProvince = (provinceIndex, flag) => {
	pickProvinceIndex = provinceIndex;
	$("#areaList").html('');
	let itemHtml = ``;
	for (var i = 0; i < city[provinceIndex].length; i++) {
		itemHtml +=
			`<div class="xpopup_list_item" onclick="selectCity('${provinceIndex}','${i}')">${city[provinceIndex][i]}</div>`;
	}
	$("#areaList").html(itemHtml);
	$("#areaBox").scrollTop(0);
	expressArea = province[provinceIndex] + '';
	if (flag == 0) {
		$('.xpopup_result .province').html(expressArea).removeClass("current");
	} else {
		$('.xpopup_result .province').html(expressArea).addClass("current");
	}
	$('.xpopup_result .city').attr("onClick", ";");
	$('.xpopup_result .province').attr("onClick", "initProvince(0);").show();
	//$("#backUp").attr("onClick", "intProvince(0);").show();
}

selectCity = (provinceIndex, cityIndex) => {
	pickCityIndex = cityIndex;

	$("#areaList").html('');
	let itemHtml = ``;
	for (var i = 0; i < district[provinceIndex][cityIndex].length; i++) {
		itemHtml +=
			`<div class="xpopup_list_item" onclick="selectDistrict('${provinceIndex}','${cityIndex}','${i}')">${district[provinceIndex][cityIndex][i]}</div>`;
	}
	$("#areaList").html(itemHtml);
	$("#areaBox").scrollTop(0);
	let selCity = city[provinceIndex][cityIndex];
	expressArea += selCity;

	if (selCity == '') {
		$('.xpopup_result .city').html(expressArea).removeClass("current");
	} else {
		$('.xpopup_result .city').html(selCity).addClass("current");
	}
	$('.xpopup_result .province').removeClass("current");
	$('.xpopup_result .district').html("").removeClass("current");
	$('.xpopup_result .city').attr("onClick", `selectCity('${provinceIndex}','${cityIndex}');`);
}

selectDistrict = (provinceIndex, cityIndex, districtIndex) => {
	pickDistrictIndex = districtIndex;
	$("#area").val('');
	let area = district[provinceIndex][cityIndex][districtIndex];
	expressArea += area;
	$('.xpopup_result .district').html(area).addClass("current");
	$('.xpopup_result .city').removeClass("current");
	let res = province[pickProvinceIndex] + city[pickProvinceIndex][pickCityIndex] + district[pickProvinceIndex][
		pickCityIndex
	][pickDistrictIndex];
	$("#area").val(res);
	hideXpopup();
}

hideXpopup = () => {
	$(".xpopup_mask").fadeOut();
	$(".xpopup_container").animate({
		"bottom": "-200%"
	});
}

showXpopup = () => {
	$(".xpopup_mask").fadeIn();
	$(".xpopup_container").animate({
		"bottom": 0
	}).attr("flag", "0");
}

onPickArea = () => {
	showXpopup()
}

onLocation = () => {
	var map = new AMap.Map('container', {
		zoom: 30,
		resizeEnable: true
	})
	var subLoading = layer.open({
		type: 2,
		content: '正在获取位置...'
	});
	AMap.plugin('AMap.Geolocation', function() {
		var geolocation = new AMap.Geolocation({
			enableHighAccuracy: true, //是否使用高精度定位，默认:true
			timeout: 10000, //超过10秒后停止定位，默认：5s
			buttonPosition: 'RB', //定位按钮的停靠位置
			buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
			zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
			needAddress: true
		});
		map.addControl(geolocation);
		geolocation.getCurrentPosition(function(status, result) {
			layer.close(subLoading);
			if (status == 'complete') {
				onComplete(result)
			} else {
				onError(result)
			}
		});
	});
}

//解析定位结果
function onComplete(data) {
	$("#address").val(data.formattedAddress);
}
//解析定位错误信息
function onError(data) {
	$("#address").val("定位失败：" + data.message);
}

handlePhone = (inputPhoneId) => {
	let phone = $(`#${inputPhoneId}`).val().trim();
	if (phone == '') {
		showToast('请输入新手机号');
		return false
	}
	if (phone.length != 11) {
		showToast('请输入11位新手机号');
		return false
	}
	if (!isValidPhoneNumber(phone)) {
		showToast('请输入11位有效手机号');
		return false
	}
	return true
}

saveAddress = () => {
	let name = $(`#name`).val().trim();
	if (name == '') {
		showToast('请输入收货人姓名');
		$(`#name`).focus();
		return
	}
	if (handlePhone('phone')) {

		let area = $("#area").val();
		if (area == '') {
			showToast('请选择所在地区');
			return
		}
		let address = $(`#address`).val().trim();
		if (address == '') {
			showToast('请填写详细地址');
			$(`#address`).focus();
			return
		}
		let tagValue = $('input[name="tag"]:checked').val();
		
		let subLoading = layer.open({
			type: 2,
			shadeClose: false,
			content: '正在提交...'
		});

		setTimeout(() => {
			layer.close(subLoading);
			showToast('操作成功！');
			goBack();
		}, 500)
	}

}
